import { ReactElement, useState, useEffect, RefObject, useRef } from 'react'
import { Space, Button, message, Form, FormInstance, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import _ from 'lodash'
// import FreeScrollBar from 'react-free-scrollbar'
import style from './index.module.less'
import DetailInfo from './components/detailInfo'
import AnchorList from './components/anchorList'
import { Context } from './context'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { getCaseDetailRequest, updateCaseDetailRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import InputBlockOne from './components/inputBlockOne'
import InputBlockTwo from './components/inputBlockTwo'
import InputBlockThree from './components/inputBlockThree'
import InputBlockFour from './components/inputBlockFour'
import InputBlockFive from './components/inputBlockFive'
import InputBlockSix from './components/inputBlockSix'
import { formatSubmitData, getInitialValuesByCaseDetail } from './util'

const { confirm } = Modal

async function initCaseDetail (id: string, formRef: RefObject<FormInstance>, setLoading: (v: boolean) => void, setCaseDetail: (v: CaseSchema) => void): Promise<void> {
  const h = message.loading('加载中', 120)
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseDetailRequest(id))
  setLoading(false)
  h()
  if (e === null && d !== null) {
    setCaseDetail(d)
    const c = formRef.current
    if (c !== null) {
      c.resetFields()
      c.setFieldsValue(getInitialValuesByCaseDetail(d))
    }
  }
}

// 更新案件数据
async function updateCaseDetail (id: string, data: { [k: string]: any }, callback: () => void): Promise<void> {
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateCaseDetailRequest(id, data))
  hide()
  if (e === null) {
    message.success('更新成功', 1).then(null, null)
    callback()
  }
}

// 提交案件数据
async function submitCaseDetail (id: string, data: { [k: string]: any }, caseDetail: CaseSchema, scoreStatus: string, refreshCaseDetail: () => void): Promise<void> {
  const d = formatSubmitData(data, caseDetail.score_status)
  if (scoreStatus !== '') {
    d.score_status = scoreStatus
  }
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateCaseDetailRequest(id, d))
  hide()
  if (e === null) {
    message.success('更新成功', 1).then(null, null)
    refreshCaseDetail()
  }
}

// 提交二次确认
function confirmToSubmit (scoreStatus: string, formRef: RefObject<FormInstance>, setScoreStatus: (v: string) => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: <span><span className={style.red}>信息提交，将无法修改，</span>你还要继续吗？</span>,
    onOk () {
      setScoreStatus(scoreStatus)
      formRef.current?.submit()
    }
  })
}

function scrollHandle (ref: RefObject<HTMLDivElement> ,setActiveAnchor: (v: string) => void): void {
  const list = ['#inputBlockOne', '#inputBlockTwo', '#inputBlockThree', '#inputBlockFour', '#inputBlockFive', '#inputBlockSix']
  const d = ref.current
  if (d === null) {
    return undefined
  }
  const o: HTMLElement | null = d.querySelector(`.${style['center-inner']}`)
  if (o === null) {
    return undefined
  }
  const top = o.scrollTop
  const cTop = o.offsetTop
  for (let i = 0; i < list.length; i++) {
    const e: HTMLElement | null = d?.querySelector(list[i])
    if (e !== null && e !== undefined) {
      if (e.offsetHeight > top - e.offsetTop + cTop) {
        setActiveAnchor(list[i])
        break
      }
    }
  }
}

const scrollFn = _.throttle(scrollHandle, 100)

interface Props {
  meta: {
    id: string
  }
}

function Main ({ meta }: Props): ReactElement {
  const ref = useRef<HTMLDivElement>(null)
  const formRef = useRef<FormInstance>(null)
  const [loading, setLoading] = useState(false)
  const [caseDetail, setCaseDetail] = useState<CaseSchema | null>(null)
  const [scoreStatus, setScoreStatus] = useState<string>('')
  const [activeAnchor, setActiveAnchor] = useState<string>('')
  const editable = caseDetail !== null && !['已确认', '已抽查', null].includes(caseDetail.score_status)
  function refreshCaseDetail (): void { initCaseDetail(meta.id as string, formRef, setLoading, setCaseDetail).catch(e => console.error(e)) }
  useEffect(() => {
    refreshCaseDetail()
    if (ref.current !== null) {
      const o = ref.current.querySelector(`.${style['center-inner']}`)
      if (o !== null) {
        function handle () {
          scrollFn(ref, setActiveAnchor)
        }
        o.addEventListener('scroll', handle)
        handle()
        return () => {
          o.removeEventListener('scroll', handle)
        }
      }
    }
  }, [ref])
  return (
    <Context.Provider value={{
      caseDetail,
      loading,
      activeAnchor,
      refreshCaseDetail,
      updateCaseDetail: async (data: { [k: string]: any }) => caseDetail !== null && await updateCaseDetail(caseDetail.id, data, refreshCaseDetail)
    }}>
       <div className={style.container} ref={ref}>
        <div className={style.left}>
          <DetailInfo />
        </div>
        <div className={style.center}>
          <div className={style['center-inner']}>
            <Form ref={formRef} layout="vertical" initialValues={getInitialValuesByCaseDetail(caseDetail)} onFinish={async d => caseDetail !== null && await submitCaseDetail(caseDetail.id, d, caseDetail, scoreStatus, refreshCaseDetail)}>
              <InputBlockOne />
              <InputBlockTwo />
              <InputBlockThree />
              <InputBlockFour />
              {
                caseDetail !== null && ['抽查中', '已抽查'].includes(caseDetail.score_status) && (
                  <>
                    <InputBlockFive />
                    <InputBlockSix />
                  </>
                )
              }
            </Form>
          </div>
        </div>
        <div className={style.right}>
          <AnchorList containerRef={ref} boundary={`.${style['center-inner']}`} />
        </div>
        {
          editable && (
            <div className={style['btn-line']}>
              <Space>
                <Button type='primary' ghost onClick={() => { setScoreStatus(''); formRef.current?.submit() }}>保存</Button>
                {['未确认', null].includes(caseDetail.score_status) && (
                  <Button type='primary' onClick={() => { confirmToSubmit('已确认', formRef, setScoreStatus) }}>确认</Button>
                )}
                {caseDetail.score_status === '抽查中' && (
                  <Button type='primary' onClick={() => { confirmToSubmit('已抽查', formRef, setScoreStatus) }}>确认抽查</Button>
                )}
              </Space>
            </div>
          )
        }
      </div>
    </Context.Provider>
  )
}

export default Main
